<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入商品标题" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="商铺编号"  v-hasPermi="['system:shop:field']" prop="shopId">
        <el-input v-model="queryParams.shopId" placeholder="请输入商铺编号" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="类目" prop="category">
        <el-cascader :show-all-levels='false' :options="cateTree" :props="props" @change="handleChange" clearable></el-cascader>
      </el-form-item>

      <el-form-item label="商品状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="商品状态" clearable>
          <el-option label="启用" value="0" />
          <el-option label="下架" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['admin:spu:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['admin:spu:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['admin:spu:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['admin:spu:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddSale" v-hasPermi="['admin:spu:AddSale']">新增特卖</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="spuList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <!-- <el-table-column label="商铺编号" align="center" prop="shopId" /> -->
      <el-table-column label="商品标题" align="center" prop="title" />
      <el-table-column label="商品logo" align="center" prop="logo">
        <template slot-scope="scope">
          <el-image style="width: 100px; height: 100px" :src="scope.row.logo" :preview-src-list="[scope.row.logo]">
          </el-image>
        </template>
      </el-table-column>

      <el-table-column label="商品销量" align="center" prop="tops" />
      <el-table-column label="商品原价格" align="center" prop="virtualPrice" />
      <el-table-column label="商品现价格" align="center" prop="realPrice" />
      <el-table-column label="商品利润值" align="center" prop="price" />
      <el-table-column label="商品消证" align="center" prop="disappear" />
      <el-table-column label="商品总库存" align="center" prop="balance" />
      <!-- <el-table-column label="商品详情-富文本形式" align="center" prop="infos" /> -->
      <!-- 商品状态 0=正常，1=下架 -->
      <el-table-column label="商品状态" align="center" prop="status">
        <template slot-scope="scope">
          {{ scope.row.status == 0? '启用': '下架' }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="商品运费" align="center" prop="shipping" />
      <el-table-column label="商品满额减运费" align="center" prop="topShipping" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['admin:spu:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['admin:spu:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1250px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="auto" :inline="true">
        <el-form-item label="商品标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="类目" prop="category">
          <el-cascader v-model="categoryArr" :show-all-levels='false' ref="tree" node-key="4" accordion :options="cateTree" :props="props" @change="handleChangeForm"></el-cascader>
        </el-form-item>

        <el-form-item label="商品销量" prop="tops">
          <el-input v-model="form.tops" placeholder="请输入商品销量" :disabled="true" />
        </el-form-item>
        <el-form-item label="商品原价格" prop="virtualPrice">
          <el-input-number v-model="form.virtualPrice"  :min="1" :max="100000000" :step="1" :precision="2"  label="请输入商品原价格"></el-input-number>
        </el-form-item>
        <el-form-item label="商品现价格" prop="realPrice">
          <el-input-number v-model="form.realPrice"  :min="1" :max="100000000" :step="1" :precision="2"  label="请输入商品现价格"></el-input-number>

        </el-form-item>
        <el-form-item v-if="isSale ==0" label="商品让利(元为单位)" prop="price">
          <el-input-number v-model="form.price"  :min="0" :max="100000000" :step="1" :precision="2"  label="请输入商品让利"></el-input-number>

        </el-form-item>
        <el-form-item label="商品消证" prop="disappear">
          <el-input-number v-model="form.disappear"  :min="0" :max="100000000" :step="1" :precision="2" :disabled="true"  label="请输入商品消证"></el-input-number>

        </el-form-item>
        <el-form-item label="商品总库存" prop="balance">
          <el-input-number v-model="form.balance"  :min="1" :max="100000000" :step="1" :precision="2"  :disabled="true" label="请输入商品总库存"></el-input-number>

        </el-form-item>

        <el-form-item label="线下商品" prop="isOffline">
          <el-switch v-model="form.isOffline" active-value="1" inactive-value="0" active-color="#13ce66" inactive-color="#666"
                    :disabled="isSale==1 || form.recommend==1 || form.isQuiz==1 || form.hotSale==1">
          </el-switch>
        </el-form-item>
        <el-form-item label="竞猜商品" prop="isQuiz">
          <el-switch v-model="form.isQuiz" active-value="1" inactive-value="0" active-color="#13ce66" inactive-color="#666"
                    :disabled="isSale==1 || form.isOffline==1 || form.recommend==1 || form.hotSale==1" >
          </el-switch>
        </el-form-item>
        <el-form-item label="热销商品" prop="hotSale">
          <el-switch v-model="form.hotSale" active-value="1" inactive-value="0" active-color="#13ce66" inactive-color="#666"
                   :disabled="isSale==1 || form.isOffline==1 || form.isQuiz==1 || form.recommend==1">
          </el-switch>
        </el-form-item>
        <el-form-item label="推荐商品" prop="recommend">
          <el-switch v-model="form.recommend" active-value="1" inactive-value="0" active-color="#13ce66" inactive-color="#666"
                    :disabled="isSale==1 || form.isOffline==1 || form.isQuiz==1 || form.hotSale==1" >
          </el-switch>
        </el-form-item>

        <!-- <div v-hasPermi="['system:shop:field']">
          <el-form-item label="特卖商品" prop="isSale">
            <el-switch v-model="form.isSale" active-value="1" inactive-value="0" active-color="#13ce66" inactive-color="#666">
            </el-switch>
          </el-form-item>

          <el-form-item v-if="form.isSale == 1" label="指定商铺" prop="shopId">
            <el-select v-model="form.shopId" placeholder="指定商铺" clearable filterable size="small">
              <el-option v-for="dict in shopListOptions" :key="dict.id" :label="dict.shopName + '---' + dict.shopMobile" :value="dict.id" />
            </el-select>
          </el-form-item>
        </div>  admin:one_area_item:add-->
        <el-form-item label="特卖商品" v-has-permi="['admin:one_area_item:add']" prop="isSale">
          <el-switch v-model="form.isSale" :active-value="1" disabled :inactive-value="0" active-color="#13ce66" inactive-color="#666">
          </el-switch>
        </el-form-item>
        <el-form-item label="商品详情" prop="infos">
          <editor v-model="form.infos" :min-height="99" />
        </el-form-item>

        <el-form-item label="商品封面" prop="logo">
          <el-upload class="avatar-uploader" :action="fileUrl" :show-file-list="false" :on-success="successFile" :before-upload="beforeAvatarUpload">
            <img v-if="form.logo" :src="form.logo" class="avatar" style="width:200px;height:200px;">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>

        <el-form-item label="商品SKU">
          <el-button size="mini" round type="success" @click="addDomain">新增商品规格</el-button>
          <div v-for="(domain,index) in form.skuList" :key="domain.key">

            <el-form-item label="规格" :prop="'skuList.' + index + '.skuName'" :rules="[
                  {required: true, message: '规格不能为空', trigger: 'blur'}
            ]">
              <el-input v-model="domain.skuName" />
            </el-form-item>
            <el-form-item label="价格" :prop="'skuList.' + index + '.skuMoney'" :rules="[
                  {required: true, message: '价格不能为空', trigger: 'blur'}
            ]">
              <el-input type="number" v-model="domain.skuMoney"></el-input>
            </el-form-item>

            <el-form-item label="库存" :prop="'skuList.' + index + '.skuBalance'" :rules="[
                  {required: true, message: '库存不能为空', trigger: 'blur'}
            ]">
              <el-input type="number" v-model="domain.skuBalance"></el-input>
            </el-form-item>
            <el-button type="danger" v-if="form.skuList.length != 1" @click.prevent="removeDomain(domain)">删除
            </el-button>
          </div>
        </el-form-item>

        <el-row>
          <el-form-item label="商品图片" prop="linkUrl">
            <el-upload class="upload-demo" :action="fileUrl" :on-preview="handlePreview" :on-remove="handleRemove" :file-list="fileList" :on-success="imagesListSuccess" :limit="6" :on-exceed="handleExceed" list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSpu, getSpu, delSpu, addSpu, updateSpu, exportSpu } from "@/api/admin/spu";
import { getCateTree, getSpucate } from "@/api/admin/spucate";
import {
  listShop
} from "@/api/admin/shop";
import { fileUrl } from "@/constant/constant"
import Editor from "@/components/Editor";

export default {
  name: "Spu",
  components: { Editor },
  data() {
    return {
      // 遮罩层
      loading: true,
      shopListOptions: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品表格数据
      spuList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //图片列表
      fileList: [],
      fileUrl: "",
      //类目树
      cateTree: [{ spucateList: [], }],
      //类目树配置
      props: {
        value: 'id',
        expandTrigger: 'hover',
        label: 'cateName',
        children: 'spucateList',
      },
      //默认值
      categoryArr: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        shopId: null,

        title: null,

        logo: null,

        tops: null,

        virtualPrice: null,

        realPrice: null,

        price: null,

        disappear: null,

        balance: null,

        infos: null,

        status: null,

        shipping: null,

        topShipping: null,

      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {

      },
      //是否特卖
      isSale: 0,
    };
  },
  created() {
    //类目树
    getCateTree().then((response) => {
      this.cateTree = response.data;
    });
    this.fileUrl = fileUrl;
    this.getList();
  },
  methods: {
    /** 查询商品列表 */
    getList() {
      this.loading = true;
      listSpu(this.queryParams).then(response => {
        this.spuList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

      listShop({ pageNum: 1, pageSize: 1000000 }).then(res => {
        this.shopListOptions = res.rows
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,

        shopId: null,

        title: null,

        logo: null,

        tops: null,

        virtualPrice: null,

        realPrice: null,

        price: null,

        disappear: null,

        balance: null,

        infos: null,

        status: 0,

        shipping: null,

        topShipping: null,

        createBy: null,

        createTime: null,

        updateBy: null,

        updateTime: null,

        skuList: [],

      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.fileList = [];
      this.form = {};
      this.categoryArr = [];

      this.reset();
      this.open = true;
      this.title = "添加商品";
    },
    /** 新增特卖按钮操作 */
    handleAddSale() {
      this.fileList = [];
      this.form = {};
      this.isSale = 1;
      this.categoryArr = [];

      this.reset();
      this.form.isSale = 1;
      this.open = true;
      this.title = "添加特卖商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.form = {};
      this.categoryArr = [],
        this.reset();
      this.fileList = [];
      const id = row.id || this.ids
      getSpu(id).then(response => {
        this.form = response.data;

        this.form.isQuiz = this.form.isQuiz + '';
        this.form.hotSale = this.form.hotSale + '';
        this.form.recommend = this.form.recommend + '';
        this.form.infos = this.form.infos + '';
        // this.form.category = this.form.category+'';
        getSpucate(this.form.category).then(response => {
          var a = response.data;
          this.categoryArr = [a.parentId, a.id];
        })


        this.open = true;
        this.title = "修改商品";

        //商品封面图片修改
        this.form.images.forEach(item => {
          this.fileList.push({
            name: item.linkUrl,
            url: item.linkUrl
          })
        })
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.warn("form", this.form);
          //商品封面图片上传
          var imagesList = [];
          this.fileList.forEach(function (item) {
            // imagesList.linkUrl = item.url
            var date = { "linkUrl": item.url }
            imagesList.push(date)
          })
          this.form.images = imagesList;
          this.form.isSale = this.isSale;

          console.warn("请求参数", this.form)

          if (this.form.id != null) {
            updateSpu(this.form).then(response => {
              if (response.code == 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgSuccess(response.msg);
              }
            });
          } else {
            addSpu(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.isSale = 0;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除商品编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delSpu(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有商品数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportSpu(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },
    removeDomain(item) {
      var index = this.form.skuList.indexOf(item)
      if (index !== -1) {
        this.form.skuList.splice(index, 1)
      }
    },
    addDomain() {
      console.warn("form = ", this.form)
      this.form.skuList.push({
        value: '',
        key: Date.now()
      });
    },
    /** 售后图片上传路径  */
    successFile(res, file) {
      this.form.logo = URL.createObjectURL(file.raw);
      this.form.logo = res.data;
    },
    imagesListSuccess(res, file) {
      this.fileList.push({
        name: res.data,
        url: res.data
      })
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg';
      const isJPG = true;
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    //表单内商品封面图片删除
    handleRemove(file, res) {
      // 查询数组中的元素，对应后删除
      this.fileList = res;
      var indexVal = -1;
    },
    //表单内商品封面图片查看
    handlePreview(file) {
    },
    //封面图片限制
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择6张图片`);
      return;
    },
    handleChange(value) {
      this.queryParams.category = value[value.length - 1];
      console.log(value[value.length - 1]);
    },
    handleChangeForm(value) {
      this.form.category = value[value.length - 1];
      console.log(value[value.length - 1]);
    },
  }
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 122px;
  height: 122px;
  line-height: 122px;
  text-align: center;
}

.avatar {
  width: 122px;
  height: 122px;
  display: block;
}
</style>
